#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include "memory.h"
#include "release_memory.h"



//declear global variables
int info[MAX_L];
int sum;
Buddy* p_tree;
void* base;
sem_t g_sem;


// start_memory() function implementation
int start_memory(int size)       // size is with unit byte
{
	int rt_val = 0;
	int i;

	sum = size; //initialize "size" bytes of memory
	printf ("memory initialized to size %d\n", sum);
sem_wait(&g_sem);
	unsigned char one = 1;
	for (i=0; i< MAX_L;i++)  //initialize an array to keep track of number of free memory blcok on each level of tree
	{
		info[i] = one<<i;
	}


	p_tree = NULL;
	p_tree = (Buddy *)malloc((2*SUM_BLK-1) * sizeof(Buddy) + size + (2*SUM_BLK-1) *sizeof(mem_header_t));
	base = (void *)&(p_tree[2*SUM_BLK-1]); //initialize base address of the block applied
	printf("The base memory address is: %p \n",base);
	
	if ( p_tree ) {
	           
		for(i=0; i<(2*SUM_BLK-1); i++)
		{
			p_tree[i].p = NULL;
			p_tree[i].left = NULL;
			p_tree[i].right = NULL;
		}	   
	

		rt_val = 1;
	} 
sem_post(&g_sem);
	return rt_val;

}




